package malus.shaofeng.com.beiwomusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.adapter.TopicCommendAdapter;
import malus.shaofeng.com.beiwomusic.model.BbsReply;
import malus.shaofeng.com.beiwomusic.model.HotPost;
import malus.shaofeng.com.beiwomusic.model.TopicPost;
import malus.shaofeng.com.beiwomusic.utils.BitmapHelper;
import malus.shaofeng.com.beiwomusic.utils.Constants;
import malus.shaofeng.com.beiwomusic.view.SildingFinishLayout;
import malus.shaofeng.com.beiwomusic.view.Topbar;

/**
 * 话题内容界面
 */
@ContentView(R.layout.activity_bbstopic)
public class BBSTopicActivity extends Activity
        implements PullToRefreshBase.OnRefreshListener2,
        Topbar.onTopbarClickListener, View.OnClickListener,
        View.OnTouchListener,TopicCommendAdapter.OnReplyEditListener {
    @ViewInject(R.id.bbs_topic_commend_list)
    PullToRefreshScrollView pullToRefreshScrollView;
    @ViewInject(R.id.sildingFinishLayout)
    SildingFinishLayout mSildingFinishLayout;
    @ViewInject(R.id.topbar)
    Topbar topbar;
    //回复或翻页的按钮，回复框
    @ViewInject(R.id.activity_bbstopic_button)
    FrameLayout flButton;
    @ViewInject(R.id.activity_bbstopic_huifu)
    LinearLayout llReply;

    private HotPost topic;
    //楼主
    TextView txtTitle;
    TextView txtNickname;
    TextView txtTime;
    TextView txtReplease;
    TextView txtContext;
    ImageView imgIcon;
    ImageView image;

    //评论列表
    private ListView commendList;
    private TopicCommendAdapter adapter;
    private ArrayList<BbsReply> data;
    //评论页码
    private int currentPage=1;
    //评论总页码
    private int totalPage=1;
    //评论数量
    private int replySize=10;

    //按钮动画
    ImageView btnAdd;
    ImageView btnHuifu;
    ImageView btnYeshu;


    private Handler onRefreshCompleteHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj instanceof PullToRefreshBase){
                PullToRefreshBase refresh = (PullToRefreshBase) msg.obj;
                if(refresh!=null){
                    refresh.onRefreshComplete();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        View inflate = LayoutInflater.from(this).inflate(R.layout.layout_bbs_topic_comment, null);
        Intent intent = getIntent();
        //获取楼主相关view
        topic = (HotPost)intent.getSerializableExtra(Constants.BundleKey.KEY_BBS_TOPIC);
        topbar.setOnTopbarClickListener(this);

        commendList = (ListView) inflate.findViewById(R.id.bbs_topic_commend_list_view);
        commendList.setDivider(null);
        commendList.setOnTouchListener(this);
        data = new ArrayList<>();

        adapter = new TopicCommendAdapter(this, data,topic,llReply,flButton);
        commendList.setAdapter(adapter);

        txtTitle=(TextView)inflate.findViewById(R.id.bbs_lz_title);
        txtNickname=(TextView)inflate.findViewById(R.id.bbs_lz_nickname);
        txtTime=(TextView)inflate.findViewById(R.id.bbs_lz_time);
        txtReplease=(TextView)inflate.findViewById(R.id.bbs_lz_replease);
        txtContext=(TextView)inflate.findViewById(R.id.bbs_lz_content);
        imgIcon=(ImageView)inflate.findViewById(R.id.bbs_lz_icon);
        image=(ImageView)inflate.findViewById(R.id.bbs_lz_image);

        btnAdd=(ImageView)inflate.findViewById(R.id.anim_button_add);
        btnHuifu=(ImageView)inflate.findViewById(R.id.anim_button_huifu);
        btnYeshu=(ImageView)inflate.findViewById(R.id.anim_button_yeshu);


        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshScrollView.setOnRefreshListener(this);


        ScrollView scrollView = pullToRefreshScrollView.getRefreshableView();
        scrollView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        scrollView.addView(inflate);
        mSildingFinishLayout
                .setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
                    @Override
                    public void onSildingFinish() {
                        BBSTopicActivity.this.finish();
                    }
                });
        initLzData();
        initReplyData(null);
    }





    /**
     * 获取评论列表
     */
    private void initReplyData(final PullToRefreshBase refreshView){
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/postReplyList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("postId",topic.getPost_id()+"");
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize",replySize+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params,new RequestCallBack<Object>() {
        private TopicPost topicPost;
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                data.clear();
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response = object.getJSONObject("response");
                    JSONObject paginator = response.getJSONObject("paginator");
                    totalPage=paginator.getInt("total_page");

                    if(!response.isNull("hot_reply")){
                        BbsReply bbsReply=new BbsReply();
                        bbsReply.parseJSON(response.optJSONObject("hot_reply"));
                        data.add(bbsReply);
                    }
                    if(!response.isNull("replies")){
                        JSONArray replies = response.getJSONArray("replies");
                        for (int i = 0; i < replies.length(); i++) {
                            JSONObject jsonObject = replies.optJSONObject(i);
                            BbsReply bbsReply=new BbsReply();
                            bbsReply.parseJSON(jsonObject);
                            data.add(bbsReply);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    if(refreshView!=null){
                        refreshView.onRefreshComplete();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(BBSTopicActivity.this,"牙买碟 ，刷新出错了>.<",Toast.LENGTH_SHORT).show();

            }
        });
    }
    /**
     * 获取楼主信息
     */
    private void initLzData() {
        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/bbs/getPost.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("postId",topic.getPost_id()+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params,new RequestCallBack<Object>() {

            private TopicPost topicPost;

            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                String msg = objectResponseInfo.result.toString();
                try {
                    JSONObject object = new JSONObject(msg);
                    JSONObject response = object.getJSONObject("response");
                    JSONObject post = response.getJSONObject("post");
                    topicPost = new TopicPost();
                    topicPost.parseJSON(post);
                    if(topicPost!=null){
                        if(topicPost.getTitle()!=null){
                            txtTitle.setText(topicPost.getTitle());
                        }
                        if(topicPost.getUser().getNickname()!=null){
                            txtNickname.setText(topicPost.getUser().getNickname());
                        }
                        if(topicPost.getCreate_time()!=null){
                            txtTime.setText(topicPost.getCreate_time().substring(0,10));
                        }
                        if(topicPost.getContent()!=null){
                            txtContext.setText(topicPost.getContent());
                        }
                        txtReplease.setText(topicPost.getReplies()+"");
                    }
                    BitmapUtils bitmapUtils = BitmapHelper.getBitmapUtils();

                    String iconUri = BitmapHelper.getImageUrl(topicPost.getUser().getFace_uri());
                    bitmapUtils.display(imgIcon, iconUri);
                    String imageUrl = BitmapHelper.getImageUrl(topicPost.getImage_uri());
                    if(imageUrl!=null&&imageUrl.length()>1){
                        bitmapUtils.display(image, imageUrl,new BitmapLoadCallBack<ImageView>() {
                            @Override
                            public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                                imageView.setVisibility(View.VISIBLE);
                                imageView.setImageBitmap(bitmap);
                            }

                            @Override
                            public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                                imageView.setVisibility(View.GONE);
                            }
                        });
                    }else{
                        image.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            if(currentPage==1){
                Toast.makeText(this,"亲，这已经是第一页啦",Toast.LENGTH_SHORT).show();
                Message msg = new Message();
                msg.obj=refreshView;
                onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
            }else{
                currentPage--;
                initReplyData(refreshView);
            }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if(currentPage>=totalPage){
            Toast.makeText(this,"亲，这已经是最后一页啦",Toast.LENGTH_SHORT).show();
            Message msg = new Message();
            msg.obj=refreshView;
            onRefreshCompleteHandler.sendMessageDelayed(msg, 200);
        }else{
            currentPage++;
            initReplyData(refreshView);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(0,R.anim.trans_slider_out);

    }

    @Override
    public void onLeftButtonClick() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);
    }

    @Override
    public void onRightButtonClick() {

    }

    @Override
    public void onSearchButtonClick() {

    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_MOVE){
            onCloseReply();
        }
        return false;
    }

    @Override
    public void onCloseReply(){
        if(llReply.getVisibility()==View.GONE){
            return;
        }
        Animation anim= AnimationUtils.loadAnimation(this,R.anim.bottom_trans_in);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llReply.setVisibility(View.GONE);
                flButton.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        llReply.startAnimation(anim);
    }

    @Override
    public void onOpenReply(final int position) {

        //如果已经有回复界面,则不执行动画
        if(llReply.getVisibility()==View.VISIBLE){
            setReplyComment(position);
            return;
        }

        //没有回复界面的话，需要先显示
        Animation anim= AnimationUtils.loadAnimation(this,R.anim.bottom_trans_out);
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

                llReply.setVisibility(View.VISIBLE);
                flButton.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if(position<0){
                    //回复楼主
                }else{
                    setReplyComment(position);
                }

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        llReply.startAnimation(anim);
    }


    private void setReplyComment(final int i) {
        final EditText content = (EditText) llReply.findViewById(R.id.layout_include_content);
        Button send=(Button)llReply.findViewById(R.id.layout_include_send);
        content.setHint("回复："+data.get(i).getUser().getNickname());

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击发送
                if(TextUtils.isEmpty(content.getText())){
                    Toast.makeText(BBSTopicActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                HttpUtils httpUtils=new HttpUtils();
                String path="http://kxai.cn/qms/ws/bbs/createPostReply.json";
                RequestParams params = new RequestParams();
                params.addBodyParameter("postId",topic.getPost_id()+"");
                params.addBodyParameter("content",content.getText().toString());
                params.addBodyParameter("refReplyId",data.get(i).getReply_id()+"");
                httpUtils.send(
                        HttpRequest.HttpMethod.POST,
                        path, params,
                        new RequestCallBack<Object>() {
                            @Override
                            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                                Toast.makeText(BBSTopicActivity.this,"评论成功>.<",Toast.LENGTH_SHORT).show();
                                onCloseReply();
                            }

                            @Override
                            public void onFailure(HttpException e, String s) {
                                Toast.makeText(BBSTopicActivity.this,"评论失败>.<",Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        });

    }


}
